<template>
  <div class="comment-item">
    <div class="comment-header">
      <img :src="comment.avatar || defaultAvatar" alt="用户头像" class="avatar">
      <div class="user-info">
        <span class="username">{{ comment.username || '匿名用户' }}</span>
        <span class="time">{{ formatTime(comment.createTime) }}</span>
      </div>
    </div>

    <div class="comment-content">
      <template v-if="comment.parentId > 0">
        <span class="reply-to">回复 @{{ comment.parentUsername }}：</span>
      </template>
      {{ comment.content }}
    </div>

    <div class="comment-actions">
      <a-button
        type="text"
        size="small"
        @click="handleReplyClick"
      >
        回复
      </a-button>
      <a-button
        type="text"
        size="small"
        :class="{ 'liked': comment.liked }"
        @click="handleLikeClick"
      >
        <template v-if="comment.liked">
          <HeartFilled />
        </template>
        <template v-else>
          <HeartOutlined />
        </template>
        {{ comment.likeCount }}
      </a-button>
    </div>

    <!-- 回复输入框 -->
    <div v-if="showReplyForm" class="reply-form">
      <CommentForm
        :target-id="comment.targetId"
        :target-type="comment.targetType"
        :parent-id="comment.id"
        :current-user-id="currentUserId"
        @on-comment-success="handleReplySubmitted"
        @on-cancel="showReplyForm = false"
      />
    </div>

    <!-- 回复列表 -->
    <div class="replies" v-if="comment.replies && comment.replies.length > 0">
      <CommentItem
        v-for="reply in comment.replies"
        :key="reply.id"
        :comment="reply"
        :current-user-id="currentUserId"
        @on-reply-success="handleSubReplySuccess"
        @on-like-success="handleReplyLikeSuccess"
      />
    </div>

    <!-- 查看更多回复 -->
    <a-button
      v-if="hasMoreReplies"
      type="text"
      size="small"
      class="load-more-replies"
      @click="loadMoreReplies"
    >
      查看更多回复
    </a-button>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { HeartOutlined, HeartFilled } from '@ant-design/icons-vue';
import CommentForm from '../components/CommentForm.vue';
import {cancelLikeCommentUsingDelete, likeCommentUsingPost,getRepliesByCommentIdUsingGet} from '@/api/commentController.ts';

// 接收的props
const props = defineProps({
  comment: {
    type: Object,
    required: true
  },
  currentUserId: {
    type: Number,
    required: true
  }
});

// 显示回复表单
const showReplyForm = ref(false);

// 回复相关状态
const repliesPage = ref(1);
const hasMoreReplies = ref(true);
const defaultAvatar = 'https://picsum.photos/id/1005/200';

// 处理回复点击
const handleReplyClick = () => {
  showReplyForm.value = !showReplyForm.value;
};

// 处理回复提交成功
const handleReplySubmitted = (newReply) => {
  showReplyForm.value = false;
  // 触发父组件事件
  emit('on-reply-success', props.comment.id, newReply);
};

// 处理点赞点击
const handleLikeClick = async () => {
  try {
    if (props.comment.liked) {
      // 取消点赞
      await   cancelLikeCommentUsingDelete (props.comment.id, props.currentUserId);
      emit('on-like-success', props.comment.id, false);
    } else {
      // 点赞
      await  likeCommentUsingPost (props.comment.id, props.currentUserId);
      emit('on-like-success', props.comment.id, true);
    }
  } catch (error) {
    console.error('处理点赞失败:', error);
  }
};

// 加载更多回复
const loadMoreReplies = async () => {
  try {
    repliesPage.value++;
    const response = await getRepliesByCommentIdUsingGet({
      commentId: props.comment.id,
      currentUserId: props.currentUserId,
      pageNum: repliesPage.value,
      pageSize: 5
    });

    if (response.data.length < 5) {
      hasMoreReplies.value = false;
    }

    // 触发父组件事件，添加更多回复
    response.data.forEach(reply => {
      emit('on-reply-success', props.comment.id, reply);
    });
  } catch (error) {
    console.error('加载更多回复失败:', error);
  }
};

// 处理子回复成功
const handleSubReplySuccess = (parentId, newReply) => {
  emit('on-reply-success', parentId, newReply);
};

// 处理回复的点赞成功
const handleReplyLikeSuccess = (replyId, liked) => {
  emit('on-like-success', replyId, liked);
};

// 格式化时间
const formatTime = (timeString) => {
  const date = new Date(timeString);
  return date.toLocaleString();
};

// 定义emit事件
const emit = defineEmits(['on-reply-success', 'on-like-success']);
</script>

<style scoped>
.comment-item {
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
}

.comment-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 12px;
}

.user-info {
  flex: 1;
}

.username {
  font-weight: 500;
  margin-right: 8px;
}

.time {
  color: #888;
  font-size: 12px;
}

.comment-content {
  margin-bottom: 8px;
  line-height: 1.5;
}

.reply-to {
  color: #888;
}

.comment-actions {
  display: flex;
  gap: 16px;
}

.comment-actions .liked {
  color: #f5222d;
}

.reply-form {
  margin-top: 12px;
  padding: 12px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.replies {
  margin-left: 52px;
  margin-top: 12px;
}

.load-more-replies {
  margin-top: 8px;
  color: #1890ff;
}
</style>
